<template>
    <div class="search-container">
         <el-input
            v-model="filterParams.keyword"
            placeholder="请输入公式名称"
            style="width: 200px"
            class="filter-item"
            clearable
            @change="emitFilterChange"
          />
          <el-button
            class="filter-item"
            type="primary"
            :icon="Plus"
            @click="handleCreate"
          >
            新增
          </el-button>
          <el-button
            class="filter-item"
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            搜索
          </el-button>
        </div>
        <el-table
          :data="tableData"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="公式名称" prop="name" min-width="180" />
          <el-table-column label="公式" prop="formula" min-width="300" />
          <el-table-column label="公式描述" prop="description" min-width="300" />
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button
                size="small" 
                type="primary"
                :icon="Edit"
                @click="handleEdit(row)"
              />
              <el-popconfirm title="确定删除该指标吗？" @confirm="handleDelete(row)">
                <template #reference>
                  <el-button
                    size="small"
                    type="danger"
                    :icon="Delete"
                  />
                </template>
              </el-popconfirm>
               
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="pagination.total"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @update:current-page="handleCurrentChange"
          @update:page-size="handlePageSizeChange"
        />
        <el-dialog v-model="dialogVisible" :title="title" width="30%" :close-on-click-modal="false">
            <el-form :model="form" ref="formRef" label-width="120px" :rules="rules">
                <el-form-item label="公式名称" prop="name">
                    <el-input v-model="form.name" clearable/>
                </el-form-item> 
                <el-form-item label="公式" prop="formula">
                    <el-input v-model="form.formula" clearable type="textarea" :rows="3"/>
                </el-form-item>
                <el-form-item label="公式描述" prop="description">
                    <el-input v-model="form.description" clearable type="textarea" :rows="3"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">保存</el-button>
            </template>
        </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive } from 'vue'
  import Pagination from '@/components/Pagination/index.vue'
  import { Delete, Edit,Plus,Search } from '@element-plus/icons-vue'



  
  const filterParams = reactive({
    keyword: '',
    category: '',
  })
  


  const dialogVisible = ref(false)
  const form = ref({
    name: '',
    formula: '',
    description: ''
  })

  const rules = reactive({
    name: [{ required: true, message: '请输入公式名称', trigger: 'blur' }],
    formula: [{ required: true, message: '请输入公式', trigger: 'blur' }],
  })
  
  const title = ref();
  const formRef = ref()

 
  const emit = defineEmits(['delete', 'edit'])
  
  interface IndicatorItem {
    id?: number
    name: string
    formula: string
    description: string
  }

  const tableData = ref([])
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 示例数据 - 实际应从API获取
  const mockData = [
    {
        id: 1,
        name: '人口密度​',
        formula: 'total_population / total_area',
        description: '人口密度 = 城市总人口 / 城市面积'
    },
    {
        id: 2,
        name: '城市化率',  
        formula: ' city_population / total_population × 100%',
        description: '城市化率 = 城镇人口数 / 总人口数 × 100%'
    },
    {
        id: 3,
        name: '人均GDP​',
        formula: '(now_gdp - last_gdp) / last_gdp × 100%',
        description: 'GDP增长率 = [(当期GDP - 上期GDP) / 上期GDP] × 100%'
    },
  ]

  const fetchData = async () => {
    console.log('fetchData')
    try {
      // 实际项目中调用API
      // const res = await getIndicatorList({ 
      //   page: pagination.currentPage,
      //   size: pagination.pageSize 
      // })
      tableData.value = mockData as any
      pagination.total = mockData.length
    } catch (error) {
      console.error('获取数据失败:', error)
    }
  }

  const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    fetchData()
  }

  const handlePageSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchData()
  }

  const emitFilterChange = () => {
    console.log('筛选条件变更:', filterParams)  
    fetchData()
  }

  const handleCreate = () => {
    formRef?.value?.resetFields()
    form.value = {
        name: '',
        formula: '',
        description: ''
    }
    dialogVisible.value = true
    title.value = '新增'
    
  }

  const handleAdd = () => {
    dialogVisible.value = false
    if(title.value === '新增'){
        tableData.value.push(form.value) as any
    }else{
        tableData.value = tableData.value.map((item: IndicatorItem) => item.id === form?.value?.id ? form.value : item) as any
    }
  }


  const handleDelete = (row: IndicatorItem) => {
    // console.log('删除指标', row);
    tableData.value = tableData.value.filter((item: IndicatorItem) => item.id !== row.id)
  }

  const handleEdit = (row: IndicatorItem) => {
    // console.log('编辑指标', row)
    title.value = '编辑'
    dialogVisible.value = true
    form.value = JSON.parse(JSON.stringify(row))
  }

  const handleSearch = () => {
    console.log('搜索指标')
  }

  defineExpose({
    fetchData
  })

  fetchData()
</script>
<style scoped lang="scss">
.search-container {
     margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
    }
}
</style>